<template>
  <div>
    <!-- 搜索框和过滤框 -->
    <div class="search">
      <form-input
        class="searchInput"
        placeholder=" 输入要查找的关卡名称"
        v-model="filterText"
        @blur="result"
      >
      </form-input>
      <el-cascader
        placeholder="请选择阶段"
        :options="FilterList"
        filterable
        :show-all-levels="false"
        :props="FilterProps"
        @change="result2"
        clearable
        v-model="nowSelect"
      ></el-cascader>
    </div>
    <!-- 增加、删除操作 -->
    <div class="operation">
      <button class="add" @click="formShow = true">增加</button>
      <button class="delete" @click="open1()">批量删除</button>
    </div>
    <!-- 增加表单 -->
    <div class="SpringFrame" v-show="formShow">
      <div class="form">
        <i class="el-icon-close" id="close" @click="close()"></i>
        <f-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <form-item label="阶段选择" prop="stageId">
            <el-cascader
              ref="myStage"
              :options="stageOptions"
              :props="stageProps"
              :show-all-levels="false"
              v-model="ruleForm.stageId"
              name="stageId"
              @change="stageChange"
            >
            </el-cascader>
          </form-item>
          <form-item label="前趋关卡" prop="lastCustomspassId">
            <el-cascader
              ref="proStage"
              :options="CheckpointsOptions"
              :props="CheckpointsProps"
              :show-all-levels="false"
              v-model="ruleForm.lastCustomspassId"
              name="lastCustomspassId"
            >
            </el-cascader>
          </form-item>
          <form-item label="关卡名称" prop="name" class="objectName">
            <form-input v-model="ruleForm.name" name="name"></form-input>
          </form-item>
          <form-item label="关卡要求" prop="region">
            <form-input
              type="textarea"
              v-model="ruleForm.region"
              name="require"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="关卡介绍" prop="type">
            <form-input
              type="textarea"
              v-model="ruleForm.type"
              name="introduce"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="关卡时间" prop="time">
            <form-input
              type="textarea"
              v-model="ruleForm.time"
              name="time"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="详细文档" prop="detaile">
            <!-- <el-upload
              name="multfile" 
              :data="itemForm" 
              class="upload-demo"
              :action= domain
              :http-request= upqiniu
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :on-change="handleChange"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2MB</div>
            </el-upload> -->
            <!-- <input type="file" name="file" id="file" /> -->
            <form enctype="multipart/form-data" id="file">
              <input type="file" name="file" id="files" />
            </form>
          </form-item>
          <form-item>
            <msg-button type="primary" @click="submitForm('ruleForm'), Show()"
              >添加</msg-button
            >
            <msg-button @click="resetForm('ruleForm')">重置</msg-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 内容展示区域 -->
    <div class="content">
      <div class="exhibition">
        <el-table id="table" :data="tableData" border style="width: 100%">
          <el-table-column
            fixed
            prop="select"
            label="所有"
            width="60%"
            align="center"
          >
            <template slot-scope="scope">
              <el-checkbox
                @change="check(scope.row)"
                :key="scope.row.customspassId"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column fixed prop="name" label="关卡名称">
            <template slot-scope="scope">
              <div slot="reference" class="twoLineCls">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="introduce" label="关卡介绍" width="460px">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="关卡介绍"
                width="200"
                trigger="hover"
                :content="scope.row.introduce"
              >
                <div slot="reference" class="twoLineCls">
                  {{ scope.row.introduce }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="content" label="关卡内容">
          </el-table-column> -->
          <el-table-column prop="require" label="关卡要求">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="关卡要求"
                width="200"
                trigger="hover"
                :content="scope.row.require"
              >
                <div slot="reference" class="twoLineCls">
                  {{ scope.row.require }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="type" label="关卡分类"> </el-table-column> -->
          <el-table-column
            prop="time"
            label="关卡时间"
            width="80px"
            align="center"
          >
            <template slot-scope="scope">
              <div slot="reference" class="twoLineCls">
                {{ scope.row.time }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100px"
            align="center"
          >
            <template slot-scope="scope">
              <alter-button
                type="text"
                size="medium"
                @click="handleEdit(scope.$index, scope.row)"
                class="el-icon-edit"
              ></alter-button>
              <alter-button
                @click.native.prevent="
                  deleteRow(scope.$index, scope.row), open()
                "
                type="text"
                size="medium"
                class="el-icon-delete"
              >
              </alter-button>
              <alter-button
                @click.native.prevent="pictureShow(scope.$index, scope.row)"
                type="text"
                size="medium"
                class="el-icon-picture-outline"
                v-show="scope.row.fileurl"
              >
              </alter-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 修改表单 -->
    <div class="editBackground" v-show="editShow">
      <div class="editTable">
        <f-form
          ref="form"
          :model="sizeForm"
          label-width="80px"
          size="medium"
          class="editForm"
          @submit.native.prevent
        >
          <form-item label="关卡名称" prop="name">
            <form-input v-model="sizeForm.name" name="name"></form-input>
          </form-item>
          <form-item label="关卡介绍" prop="introduce">
            <form-input
              type="textarea"
              v-model="sizeForm.introduce"
              name="introduce"
              resize="none"
              rows="6"
            ></form-input>
          </form-item>
          <form-item label="关卡要求" prop="require">
            <form-input
              type="textarea"
              v-model="sizeForm.require"
              name="require"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="关卡时间" prop="time">
            <form-input
              type="textarea"
              v-model="sizeForm.time"
              name="time"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="详细文档" prop="detaile">
            <form enctype="multipart/form-data" id="editFile">
              <input type="file" name="editFile" id="editFiles" />
            </form>
          </form-item>
          <form-item size="large">
            <alter-button type="primary" @click="onSubmit(), Show()"
              >修改</alter-button
            >
            <alter-button @click="cancle">取消</alter-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 展示图片 -->
    <div class="demo-image" v-show="imgShow" @click="imgShow = false">
      <el-image
        style="width: 900px; height: 400px"
        :src="imgurl"
        fit="contain"
      ></el-image>
    </div>
    <!-- 展示分页 -->
    <div class="paging">
      <el-pagination
        background
        :page-size="pageSize"
        :page-sizes="[7, 10, 15, 20]"
        :current-page="currentPage"
        layout="total,sizes,prev, pager, next,jumper"
        :total="tablesLength"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import "@/assets/css/resourceManegement.css";
import $ from "jquery";
import { mapMutations } from "vuex";
import { mixin } from "@/mixin.js";
import {SearchAllSubjectAPI,DeleteAllCheckPAPI,AddCheckPointsAPI,AddCheckPointsPctureAPI,UpdateCheckPointsAPI,SelectCheckPointsAPI } from "@/api/utils";
export default {
  mixins: [mixin],
  async mounted() {
    // this.result();
    this.handleCurrentChange(1);
    const res = await SearchAllSubjectAPI();
    if (res.data.flag) {
      var array = res.data.data;
      //把 array 中名为custompassList替换为stageList，为了练级器能显示
      let brray = JSON.parse(
        JSON.stringify(array).replace(/subjectId/g, "stageId")
      );
      this.FilterList = brray;
      this.stageOptions = array;
    } else {
      this.$message.error("请求失败！");
    }
  },
  data() {
    return {
      //搜索框
      filterText: "",
      //过滤框
      nowSelect: "",
      //过滤框下拉内容
      FilterList: [],
      tablesLength: 0,
      currentStage: 0,
      currentSubId: 1,
      FilterProps: {
        value: "stageId",
        label: "name",
        children: "stageList",
      },
      tableData: [],
      nowSelect: "",
      formShow: false,
      //修改表单中的内容
      sizeForm: {
        name: "",
        introduce: "",
        require: "",
        // type: "",
        time: "",
      },
      ifRequest: true,
      editShow: false,
      currentPage: 1,
      // 放置勾选的 id
      Selection: [],
      stageOptions: [],
      CheckpointsOptions: [],
      CheckpointsProps: {
        value: "customspassId",
        label: "name",
      },
      // 图片显示与隐藏
      imgShow: false,
      imgurl: "",
      //下拉列表props指定
      stageProps: {
        value: "stageId",
        label: "name",
        children: "stageList",
      },
      imageUrl: "",
      qiniuaddr: "",
      itemForm: {
        user_name: "",
        head_img: "",
      },
      pageSize: 7,
      // 表单配置
      ruleForm: {
        name: "",
        type: "",
        resource: "",
        region: "",
        desc: "",
        detaile: "",
        stageId: "",
        lastCustomspassId: [],
        time: "",
      },
      // 表单中的相关规则配置
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: "请填写关卡介绍", trigger: "blur" }],
        stageId: [{ required: true, message: "请选择阶段", trigger: "change" }],
        lastCustomspassId: [
          { message: "请选择关卡", trigger: "change", type: "array" },
        ],
        // resource: [
        //   { required: true, message: "请选择一个关卡类型", trigger: "change" },
        // ],
        region: [
          { required: true, message: "请填写关卡要求", trigger: "blur" },
        ],
        desc: [{ required: true, message: "请填写关卡内容", trigger: "blur" }],
        time: [{ required: true, message: "请填写关卡时间", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 修改一页展示的内容
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(1);
      // this.getPageData();
    },
    // 存储所有要删除的数据
    check(i) {
      //  关卡id
      if (this.Selection.indexOf(i.customspassId) == -1) {
        this.Selection.push(i.customspassId);
      } else {
        this.Selection = this.Selection.filter(
          (item) => item != i.customspassId
        );
      }
      // console.log(this.Selection);
    },
    // 删除全部操作
    async DeleteAll() {
      //调用后端接口,传入 this.Selection
      return DeleteAllCheckPAPI(this.Selection).then(res=>{
        if (res.data.flag) {
            this.Show();
            this.editShow = false;
            this.PageRefresh();
            this.$message.success("删除成功!");
          } else {
            this.$message.error("删除失败!");
          }
      })
    },
    // 删除按钮判断
    open1() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.DeleteAll();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.PageRefresh();
        });
    },
    // 页面刷新
    ...mapMutations("Refresh", { Show: "Show" }),
    // 级联框过滤
    result2(v) {
      if (v.length == 0) {
        this.currentSubId = 1;
        this.currentStage = "";
      } else {
        this.currentSubId = v[0];
        this.currentStage = v[1];
      }
      this.handleCurrentChange(1);
    },
    // 过滤
    result() {
      this.handleCurrentChange(1);
    },
    // 表单方法
    async submitForm(formName) {
      //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.CheckpointsOptions.length) {
            this.lstCustomspassId = this.ruleForm.lastCustomspassId[0];
          } else {
            this.lstCustomspassId = 0;
          }
          this.stgId = parseInt(this.ruleForm.stageId);
          this.CheckName = this.ruleForm.name;
          //获取所有的表单中的内容
          // var params = $(".demo-ruleForm").serializeArray()
          var formFile = new FormData();
          var imgfile = document.querySelector("#files");
          var file = imgfile.files[0];
          formFile.append("file", file);
          //把从表单获取过来的值存储为对象
          // let array = {};
          // params.forEach((element) => {
          //   array[element.name] = element.value;
          // });
          //获取当前级联选择的阶段名
          this.stageName =
            this.$refs.myStage.getCheckedNodes()[0].pathLabels[1];
          //找到对应的阶段id
          this.stageOptions.forEach((element) => {
            element.stageList.forEach((el) => {
              if (el.name == this.stageName) {
                this.CheckPointId = el.stageId;
              }
            });
          });
          return AddCheckPointsAPI(this.CheckPointId,this.lstCustomspassId,this.ruleForm.name,this.ruleForm.type,this.ruleForm.region,this.ruleForm.time).then(res=>{
             if (res.data.flag) {
                // 增加成功
                this.pictureId = res.data.data;
                var that = this;
                // 上传图片
                if (file) {
                  formFile.append("pictureId", this.pictureId);
                  return AddCheckPointsPctureAPI(formFile).then(res=>{
                    if (res.data.flag) {
                        that.Show();
                        that.editShow = false;
                        that.PageRefresh();
                        that.$message.success("图片增加成功！")
                      }
                  })
                } else {
                  this.Show();
                  this.editShow = false;
                  this.PageRefresh();
                  this.$message.success("增加成功!");
                }
              } else {
                this.Show();
                this.editShow = false;
                this.PageRefresh();
                this.$message.error("增加失败!");
              }
          })
        }else{
          this.PageRefresh();
          this.$message.error("表单有空值，增加失败！")
        }
      });
    },
    // 编辑按钮
    handleEdit(index, rows) {
      // console.log(rows);
      this.editShow = true;
      this.sizeForm.name = rows.name;
      this.sizeForm.introduce = rows.introduce;
      // this.sizeForm.content = rows.content;
      this.sizeForm.time = rows.time;
      this.sizeForm.require = rows.require;
      this.sizeForm.type = rows.type;
      this.currentId = rows.customspassId;
    },
    //修改表单提交
    async onSubmit() {
      var params = $(".editForm").serializeArray();
      // let array = {};
      // array.customspassId = this.currentId;
      //判断表单不能为空，且获取到数据
      params.forEach((element) => {
        if (element.value == "") {
          this.ifRequest = false;
          this.$message.error("表单不能为空!");
          this.PageRefresh();
        }
        // else {
        // 把表单中获取到的值转化为对象形式
        // array[element.name] = element.value;
        // }
      });
      //把对象转换为 jsonp 格式
      if (this.ifRequest) {
        // array = JSON.stringify(array);
        var formFile = new FormData();
        var imgfile = document.querySelector("#editFiles");
        var file = imgfile.files[0];
        formFile.append("file", file);
        // 进行修改操作
        return UpdateCheckPointsAPI(this.currentId,this.sizeForm.name,this.sizeForm.introduce,this.sizeForm.require,this.sizeForm.time).then(res=>{
           if (res.data.flag) {
              // 增加成功
              // 上传图片
              if (file) {
                formFile.append("pictureId", this.currentId);
                var that = this;
                return AddCheckPointsPctureAPI(formFile).then(res=>{
                   if (res.data.flag) {
                      that.Show();
                      that.editShow = false;
                      that.PageRefresh();
                      that.$message.success("修改成功!");
                    }
                })
              } else {
                this.Show();
                this.editShow = false;
                this.PageRefresh();
                this.$message.success("修改成功!");
                // this.$message.error("请添加图片!");
              }
            }
        })
      }
    },
    //删除操作
    // 获取删除的对象对应的id、名字等
    deleteRow(index, rows) {
      this.customspassId = rows.customspassId;
    },
    //执行删除操作
    async ExecuteDelete() {
      return DeleteAllCheckPAPI(this.customspassId).then(res=>{
         if (res.data.flag) {
            // alert('删除成功')
            this.Show();
            this.editShow = false;
            this.PageRefresh();
            this.$message.success("删除成功!");
          } else {
            this.$message.error("删除失败!");
          }
      })
    },
    // 查看图片
    pictureShow(index, rows) {
      // console.log(rows);
      this.imgurl = "http://" + rows.fileurl;
      this.imgShow = true;
    },
    //阶段选择发生变化
    async stageChange() {
      // 可以根据阶段 id找关卡
      return SearchAllSubjectAPI().then(res=>{
         if (res.data.flag) {
            const Alldata = res.data.data;
            Alldata.forEach((element) => {
              element.stageList.forEach((el) => {
                if (
                  el.name ==
                  this.$refs.myStage.getCheckedNodes()[0].pathLabels[1]
                ) {
                  this.CheckpointsOptions = el.customspassList;
                }
              });
            });
          }
      })
    },
    //当前在第几页
    async handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      return SelectCheckPointsAPI(this.currentSubId,this.currentStage,this.filterText,this.currentPage,this.pageSize).then(res=>{
        if(res.data.flag){
          this.tablesLength = res.data.data.page.pageTotal;
            let user = res.data.data.customspassList;
            this.tableData = user;
        }else{
           this.$message.error('查询失败！');
        }
      })
    },
  },
};
</script>

<style scoped>
.search /deep/ .el-cascader {
  height: 40px;
}
/* 增加表单样式 */
.editTable /deep/ form input {
  margin: 0 !important;
}
.form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 670px;
  max-height: 650px;
  background-color: white;
  padding-left: 135px;
  padding-top: 30px;
  box-sizing: border-box;
  border-radius: 15px;
}
.form /deep/form input {
  margin: -3px;
}
.form /deep/.el-form demo-ruleForm {
  width: 450px;
  height: 500px;
}
.form /deep/.el-form-item__content {
  width: 300px;
}
#close {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  cursor: pointer;
  color: #ccc;
}

/* 修改表单 */
.editBackground {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 98;
  background-color: rgba(0, 0, 0, 0.5);
}
.editTable {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 588px;
  max-height: 520px;
  padding: 20px 67px;
  background-color: white;
  border-radius: 10px;
  box-sizing: border-box;
  z-index: 99;
}
.editTable /deep/.el-input {
  width: 40%;
}
.editTable /deep/.el-textarea {
  width: 65%;
}
.paging {
  width: 100%;
  height: 30px;
  margin-bottom: 0;
  text-align: center;
}
/* 查看图片 */
.demo-image {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 50;
}
/* 经过展示关卡介绍 */
.twoLineCls {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
}
.searchInput /deep/.el-input__inner {
  border: 3px solid #dcdfe6;
}
.search /deep/.el-cascader .el-input .el-input__inner {
  border: 3px solid #dcdfe6;
}
.el-table--border {
  border: 3px solid #ebeef5;
}
.exhibition /deep/.el-table .cell {
  color: #666;
}
.exhibition /deep/.twoLineCls {
  color: black;
}
.exhibition /deep/.el-table th.el-table__cell,
.exhibition /deep/.el-table tr,
.exhibition /deep/.el-table {
  background-color: rgba(255, 255, 255, 0.3);
}
</style>